package webshop.model.bl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import webshop.model.db.Customer;
import webshop.model.sf.HibernateUtil;

public class CustomerManager {
	
	public Customer getCustomer(String username, String password) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Customer> customer = session.createCriteria(Customer.class)
				.add(Restrictions.and(
						Restrictions.eq("username", username),
						Restrictions.eq("password", password))).list();
		
		session.getTransaction().commit();
		
		return customer == null || customer.size() == 0 ? null : customer.get(0);
	}
	
	public void saveCustomer(Customer customer) {
		customer.setIsAdmin(false);
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		session.save(customer);
		
		session.getTransaction().commit();
	}

	public boolean usernameExists(String username) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		
		session.beginTransaction();
		
		@SuppressWarnings("unchecked")
		List<Customer> customer = session.createCriteria(Customer.class)
				.add(Restrictions.eq("username", username)).list();
		
		session.getTransaction().commit();
		
		return customer == null || customer.size() == 0 ? false : true;
	}
}
